package com.example.a2105_ivideo

import android.app.Application
import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.example.lib_common.BaseApplication

import com.example.lib_common.utils.LoggerUtils
import com.example.lib_log.crash.CrashHandler
import com.tencent.android.tpush.XGIOperateCallback
import com.tencent.android.tpush.XGPushConfig
import com.tencent.android.tpush.XGPushManager
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import com.umeng.analytics.MobclickAgent
import com.umeng.commonsdk.UMConfigure
import me.jessyan.autosize.AutoSizeConfig
import okhttp3.Call
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.Executors

private const val s = "umeng"

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/21
 */
class App:BaseApplication() {
    companion object{
        val TAG = "App"
    }
    override fun onCreate() {
        super.onCreate()

        val start = System.currentTimeMillis()
//冷启动优化方案
//        // 分级初始化
//        StartupManager.init(this) {
//            add(CoreLibraryInitTask()) // 主线程同步执行
//            addAsync(LogLibraryInitTask()) // 后台线程执行
//            addDelay(AdvertisementInitTask(), 5000) // 延迟执行
//        }.start()
        //不必须初始化放在异步中
        Executors.newCachedThreadPool()
            .submit{
                initMMKV()
                initArouter()
                initBuly()
                initPush()
            }


        initUmeng()
        initAutoSize()
        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","application的onCreate 耗时:${end-start}")
    }

    private fun initAutoSize() {
        val start = System.currentTimeMillis()
        // 初始化 AutoSize
        AutoSizeConfig.getInstance()
            .setCustomFragment(true) // 是否支持自定义 Fragment
            .setBaseOnWidth(true)    // 是否以宽度为基准进行适配
            .setDesignWidthInDp(411) // 设计稿的宽度（单位：dp）
            .setDesignHeightInDp(890); // 设计稿的高度（单位：dp）
        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","initAutoSize 耗时:${end-start}")
    }

    private fun initPush() {
        val start = System.currentTimeMillis()
        //1:注册推送
        XGPushConfig.enableDebug(this,true)
        XGPushManager.registerPush(this,object : XGIOperateCallback {
            override fun onSuccess(token: Any?, flag: Int) {
                LoggerUtils.d(TAG,"注册成功token:$token")
                MMKV.defaultMMKV().encode("push_token",token.toString())
                //2:绑定推送token
                val push_token = MMKV.defaultMMKV().decodeString("push_token")
                val formBody = FormBody.Builder()
                    .add("pushToken", push_token!!)
                    .build()
                val client = OkHttpClient.Builder()
                    .build()
                val request = Request.Builder()
                    .url("http://10.161.54.197:8887/push/bindPushToken")
                    .post(formBody)
                    .header("token","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJjYWl5aWxpbiIsImV4cCI6MTc0MTc0NjczNX0.oK17rjvigFRpQQM3KhpL6eetOfKyhJUKpshFfxHMFhg")
                    .build()
                client.newCall(request).enqueue(object :okhttp3.Callback{
                    override fun onFailure(call: Call, e: IOException) {
                        LoggerUtils.d("TouchActivity","绑定失败 ${e.message}")
                    }

                    override fun onResponse(call: Call, response: Response) {
                        LoggerUtils.d("TouchActivity","绑定成功 ${response.body?.string()}")

                    }
                })
            }

            override fun onFail(data: Any?, errCode: Int, msg: String?) {
                LoggerUtils.d(TAG,"注册失败errCode:$errCode msg:$msg")

            }
        })
        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","initPush 耗时:${end-start}")
    }

    private fun initUmeng() {
        val start = System.currentTimeMillis()
        //友盟
        //情况一：第一次冷启动：没同意（1）application预初始化 （2）点击同意正式初始化
        //情况二：下次冷启动：同意 （1）application预初始化 （2）【异步中】正式初始化，冷启动优化
        //预初始化：不耗时，不需要用户同意，不会采集上报用户信息
        UMConfigure.setLogEnabled(true);
        UMConfigure.preInit(this,"667a78dc940d5a4c4976ea5f","umeng")
        //正式初始化：比较耗时，最好放在异步中延迟，冷启动优化
        if (MMKV.defaultMMKV().decodeBool("agree")){
            Executors.newCachedThreadPool()
                .submit {
                }
            UMConfigure.init(this,"667a78dc940d5a4c4976ea5f","umeng",UMConfigure.DEVICE_TYPE_PHONE, "")

        }
        //页面采集方式
        // 自动采集：activity 不需要写代码
//        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO)
        //手动采集选择：activity和fragment 需要写代码
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.MANUAL)

        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","initUmeng 耗时:${end-start}")
    }

    private fun initBuly() {
        val start = System.currentTimeMillis()
        //bugly初始化
        MMKV.defaultMMKV().encode("agree",true) //true
        if (MMKV.defaultMMKV().decodeBool("agree")){
            CrashReport.initCrashReport(this, "fa36510fb8", true)
//            CrashReport.setDeviceId()//设置设备id
//            CrashReport.setDeviceModel()//设置设备机型
        }
        //自己封装崩溃收集
        CrashHandler.getInstance().init(this)
        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","initBuly 耗时:${end-start}")
    }

    private fun initMMKV() {
        val start = System.currentTimeMillis()
        MMKV.initialize(this)
        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","initMMKV 耗时:${end-start}")
    }

    private fun initArouter() {
        val start = System.currentTimeMillis()
        ARouter.openLog()
        ARouter.openDebug()
        ARouter.init(this)
        LoggerUtils.d(TAG,"app初始化成功")
        val end = System.currentTimeMillis()
        LoggerUtils.d("启动优化","initArouter 耗时:${end-start}")
    }
}